#!/usr/bin/env bash
# 时区 / BBR / Swap / 关闭IPv6 / 修 raw.githubusercontent.com
set -Eeuo pipefail

type log_info >/dev/null 2>&1 || { echo "[optimize] _common.sh 未加载"; exit 1; }

set_timezone_shanghai() {
  ensure_root
  timedatectl set-timezone Asia/Shanghai
  timedatectl status
  log_info "时区已设置为 Asia/Shanghai"
}

enable_bbr() {
  ensure_root
  if ! grep -q "tcp_congestion_control" /etc/sysctl.conf 2>/dev/null; then
    echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
    echo "net.ipv4.tcp_congestion_control=bbr" >> /etc/sysctl.conf
  fi
  sysctl -p
  sysctl net.ipv4.tcp_congestion_control
  log_info "BBR 已尝试启用（重启后更稳）"
}

setup_swap_interactive() {
  ensure_root
  read -rp "输入 swap 大小（如 1G/2G）: " S
  [ -z "$S" ] && { echo "未输入"; return 1; }
  if swapon --show | grep -q swapfile; then
    log_warn "检测到已有 /swapfile"
  fi
  fallocate -l "$S" /swapfile
  chmod 600 /swapfile
  mkswap /swapfile
  swapon /swapfile
  grep -q "/swapfile" /etc/fstab || echo "/swapfile none swap sw 0 0" >> /etc/fstab
  swapon --show
  log_info "Swap 已配置完成：/swapfile (${S})"
}

disable_ipv6_persistent() {
  ensure_root
  sysctl -w net.ipv6.conf.all.disable_ipv6=1
  sysctl -w net.ipv6.conf.default.disable_ipv6=1
  echo -e "net.ipv6.conf.all.disable_ipv6=1\nnet.ipv6.conf.default.disable_ipv6=1" >/etc/sysctl.d/99-disable-ipv6.conf
  sysctl --system
  log_info "IPv6 已禁用（运行时+持久化）"
}

fix_github_raw_hosts() {
  ensure_root
  if ! grep -q "raw.githubusercontent.com" /etc/hosts; then
    echo "185.199.108.133 raw.githubusercontent.com" >> /etc/hosts
    log_info "已向 /etc/hosts 添加 raw.githubusercontent.com → 185.199.108.133"
  else
    log_warn "/etc/hosts 已存在 raw.githubusercontent.com 条目"
  fi
}
